<template>
  <a-modal
    :title="formTile + '人群划分'"
    :visible="true"
    width="60%"
    :footer="null"
    @cancel="reset"
  >
    <div class="main">
      <a-card>
        <a-row
          type="flex"
          justify="start"
          align="top"
        >
          <a-col :span="24">
            <a-form
              :form="form"
              @submit="handleSubmit"
              :labelCol="formItemLayout.labelCol"
              :wrapperCol="formItemLayout.wrapperCol"
            >

              <a-form-item
                label="查询数据源"
                :required="true"
              >
                <a-select
                  allow-clear
                  show-search
                  placeholder="请选择查询数据源"
                  optionFilterProp="children"
                  @change="onchange"
                  v-decorator="[
                  'dataSourceKey',
                  {
                    rules: [{ required: true, message: '请选择查询数据源!' }]
                  }
                ]"
                >
                  <a-select-option
                    :value="item.id"
                    v-for="(item,index)  in menuType"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                label="人群划分业务名称"
                :required="true"
              >
                <a-input
                  allow-clear
                  placeholder="请输入人群划分业务名称"
                  v-decorator="[
                  `peopleName`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入人群划分业务名称'
                      },
                    ]
                  }
                ]"
                />
              </a-form-item>
               <a-form-item
                label="是否替换APPID"
                :required="true"
              >
                <a-switch @change="changeSwitch"
                v-decorator="[
                  'replaceDataStatus',
                  { initialValue: false, valuePropName: 'checked', rules: [{ required: true, message: '请选择是否分页！' }] },
                ]"
                ></a-switch>
              </a-form-item>
               <a-form-item
                label="APPID替换字段"
                :required="true"
                v-if="showAppid"
              >
                <a-input
                  allow-clear
                  placeholder="请输入APPID替换字段"
                  v-decorator="[
                  `getAppidStr`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入APPID替换字段'
                      },
                    ]
                  }
                ]"
                />
              </a-form-item>
              <a-form-item
                label="SQL语句"
              >
                <div class="button">
                  <a-button @click="check">检验SQL</a-button>
                </div>
                <a-textarea
                  allow-clear
                  :rows="8"
                  placeholder="请输入查询SQL语句"
                  v-decorator="['executeSql', { rules: [{ required: true, message: '请输入查询SQL语句' }] }]"
                ></a-textarea>
                <p style="color:red">总记录数：{{countRecord}}</p>
              </a-form-item>
              <a-form-item label="语句标签列表">
                <div
                  style="border: 1px solid #d9d9d9;height: 130px;padding: 20px;"
                >
                  <span
                    v-for="(item,index) in fieldList"
                    :key="index"
                  >
                    <a-tag color="blue" class="tag">
                      {{'${'+item+'}'}}
                    </a-tag>
                  </span>
                </div>
              </a-form-item>
              <a-form-item
                label="是否分页"
                :required="true"
              >
                <a-switch v-decorator="[
                  'pageStatus',
                  { initialValue: false, valuePropName: 'checked', rules: [{ required: true, message: '请选择是否分页！' }] },
                ]"></a-switch>
              </a-form-item>
             
              <a-row style="margin-top:10px">
                <a-col
                  :span="16"
                  :offset="18"
                  class="info-action"
                >
                  <a-button @click="clear">
                    重置
                  </a-button>
                  <a-button
                    :style="{ marginLeft: '8px' }"
                    type="primary"
                    html-type="submit"
                    :loading="loading"
                  >
                    保存
                  </a-button>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
      </a-card>
    </div>

  </a-modal>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
export default {
  props: {
    content: {
      type: Object,
      default: null
    },
    appid: {
      type: String,
      default: null
    }
  },

  data() {
    return {
      urlKey: 'basemgt-wx',
      menuType: [],
      dataSourceName:'',
      fieldList: [],
      dbType: '',
      id: '',
      showAppid:false,
      tags: [],
      placeholderDetailList: [],
      type: 1,
      inputVisible: false,
      inputValue: '',
      inputContent: '',
      dataSourceKey: '',
      countRecord:'',
      formItemLayout: {
        labelCol: {
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xl: { span: 18 },
          xs: { span: 18 },
          sm: { span: 18 }
        }
      },
      loading: false,
      form: this.$form.createForm(this),
      add: false
    }
  },

  created() {
    const { content } = this.$props
    console.log(content)
    if (content) {
      this.formTile = '编辑'
      this.id = content.id
      this.type = content.type
      this.$nextTick(() => {
        this.form.setFieldsValue({
          type: content.type,
          name: content.name,
          dataSourceKey: content.dataSourceKey,
          desc: content.describe,
          executeSql: content.sqlStatement
        })
      })
      this.getDetailList()
    } else {
      this.formTile = '新增'
      this.add = true
    }
  },
  watch: {
    appid() {
      this.getMenuList()
    }
  },
  mounted() {
    this.getMenuList()
  },
  methods: {
    reset() {
      this.form.resetFields()
      this.fieldList = []
      this.$emit('close')
    },
    clear() {
      this.form.resetFields()
      this.fieldList = []
    },
    getMenuList() {
      const params = {}
      getAction(`${this.urlKey}/WxPlaceHolder/findDataSourceInfo`, params).then(data => {
        if (data.code == 200) {
          this.menuType = data.data
        } else {
          this.$message.warning(data.msg || data.message)
        }
      })
    },
    changeSwitch(value){
      this.showAppid = value
    },
    getDetailList() {
      const params = {
        id: this.id
      }
      getAction(`${this.urlKey}/WxPlaceHolder/findWxPlaceHolderDetailById`, params).then(data => {
        if (data.code == 200) {
          if (this.type == 1) {
            const arr = []
            data.data.placeholderDetailList.map(item => {
              const subitem = {
                aliasName: item.topicTagName,
                column: item.fieldName
              }
              arr.push(subitem)
            })
            this.fieldList = arr
          } else {
            data.data.placeholderDetailList.map(item => {
              const obj = {
                name: item.fieldName,
                desc: item.describe
              }
              this.tags.push(obj)
            })
          }
        } else {
          this.$message.warning(data.msg || data.message)
        }
      })
    },
    onchange(values) {
      this.menuType.map(item => {
        if (values == item.id) {
          this.dataSourceName = item.name
        }
      })
    },
    check() {
      this.fieldList = []
      const newArr = this.form.getFieldsValue()
      console.log(newArr)
      if (!newArr.dataSourceKey) {
        this.$message.warning('请选择数据源！')
      } else if (!newArr.executeSql) {
        this.$message.warning('请填写SQl语句！')
      } else if (!newArr.getAppidStr && this.showAppid) {
        this.$message.warning('请输入APPID替换字段！')
      } else {
        const params = {
          sqlStr: newArr.executeSql,
          datasourceKey: newArr.dataSourceKey,
          replaceDataStatus : this.showAppid ? 1 :0,
          getAppidStr:this.showAppid?newArr.getAppidStr:''
        }
        postAction(`${this.urlKey}/sqlManager/getSqlManagerInfo`, params).then(data => {
          if (data.code == 200) {
            this.fieldList = data.data.fieldList
            this.countRecord = data.data.countRecord
          } else {
            this.$message.warning(data.msg)
          }
        })
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.submit(values)
        }
      })
    },
    submit(values) {
      console.log(values);
      var params = values
      params.pageStatus = params.pageStatus ? 1:0
      params.appid = this.appid
      params.dataSourceName = this.dataSourceName
      params.replaceDataStatus = params.replaceDataStatus ? 1:0
      const newArr = []
      this.fieldList.map((item)=>{
        const obj = {
          name:'${' + item +'}'
        }
        newArr.push(obj.name)
      })
      params.fieldList = newArr
      console.log(params);
      if (this.id) {
        params.id = this.id
      }
      if (!params.fieldList.length) {
        this.$message.warning('请先校验SQL！')
      } else {
        const api = this.add ? `${this.urlKey}/managerPeopleRecord/insertWxManagerPeopleRecord` : `${this.urlKey}/WxPlaceHolder/updateWxPlaceHolder`
        postAction(api, params).then(data => {
          if (data.code == 200) {
            this.$message.success(this.add ? '新建成功！' : '修改成功！')
            this.reset()
          } else {
            this.$message.warning(data.msg || data.message)
          }
        })
      }
    }
  }
}
</script>
<style scoped>
.button {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 5px;
}
.tag{
    font-size: 16px;
}

</style>
<style>
#executeSql{
      font-weight: 500;
    font-size: 16px;
}
</style>